<?php
/**
 * Created by PhpStorm.
 * User: liu85
 * Date: 2018/11/23
 * Time: 23:17
 */

namespace app\common\utils;


use app\common\consts\BaseConst;
use think\facade\Config;
use think\facade\Cookie;

class MyCrypt
{
    /**
     * 生成密码
     * @param $pass
     * @return string
     */
    public static function makePassword($pass)
    {
        $pass = BaseConst::DEFAULT_PASS_PREFIX . $pass;
        return md5($pass);
    }

    /**
     * 生成登录token
     * @return string
     */
    public static function makeToken()
    {
        $pass = BaseConst::DEFAULT_PASS_PREFIX . uniqid(mt_rand(100000, 999999)) . mt_rand(100000, 999999);
        return md5($pass);
    }

    /**
     * 生成随机码
     * @author liud
     * @param $length
     * @param $isNumber
     * @return mixed
     */
    public static function makeCode($length,$isNumber=false)
    {
        $rand = [1,2,3,4,5,6,7,8,9,0];
        if(!$isNumber){
            for($i=65;$i<91;$i++){
                $rand[] = strtolower(chr($i));
                $rand[] = strtoupper(chr($i));
            }
        }
        $str = '';
        for($i=0;$i<$length;$i++){
            $key = array_rand($rand);
            $str.=$rand[$key];
        }
        return $str;
    }

    /**
     * 验证签名
     * @author liud
     * @param $method
     * @param $uri
     * @param $params
     * @return bool
     */
    public static function verifySignature($method,$uri,$params)
    {
        if(isset($params['_debug'])){
            return true;
        }

        if(Cookie::get('app_debug') == BaseConst::APP_DEBUG){
            return true;
        }
        if(!isset($params['sign'])){
            return false;
        }
        $sign = $params['sign'];
        unset($params['sign']);
        ksort($params);
        $newList = [];
        foreach($params as $k=>$v){
            $newList[] = $k.'='.$v;
        }
        $str = implode('&',$newList);
        $str = $method.$uri.'?'.$str.Config::get('app_secret');
        if(md5($str) == $sign){
            return true;
        }
        return false;
    }
}